/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SessionBeans.entites;

import SessionBeans.actions.OperationTypeEnum;
import SessionBeans.logs.FolderChangeLogService;
import entities.Folder;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Tomas
 */
@Stateless
@LocalBean
public class FolderService {
    @EJB
    private FolderChangeLogService folderChangeLogService;
    @PersistenceContext(unitName = "tCloudEE-ejbPU")
    private EntityManager em;
    
    public Folder newFolder(Long userId, String name, Long parentFolderId){
        Folder parentFolder = em.find(Folder.class, parentFolderId);
        
        return newFolder(userId, name, parentFolder);
    }
    
    public Folder newFolder(Long userId, String name, Folder parentFolder){
        Folder folder = new Folder(null, name, 0);
        folder.setParentFolder(parentFolder);
        
        folder = em.merge(folder);
        em.flush();
        
        folderChangeLogService.addLogRow(userId, folder, OperationTypeEnum.NEW);
        
        return folder;
    }
    
    public Folder newFolder(Long userId, String name){
        Folder folder = new Folder(null, name, 0);
        //folder.setParentFolder(parentFolder);
        
        folder = em.merge(folder);
        em.flush();
        
        folderChangeLogService.addLogRow(userId, folder, OperationTypeEnum.NEW);
        
        return folder;
    }
    
    public void updateFolder(Long userId, Long folderId, String name){
        Folder find = em.find(Folder.class, folderId);
        
        updateFolder(userId, find, name);
    }
    
    public void updateFolder(Long userId, Folder folder, String name){
        folder.setName(name);
        em.persist(folder);
        
        folderChangeLogService.addLogRow(userId, folder, OperationTypeEnum.UPDATE);
    }

    public void deleteFolder(Long userId, Long folderId){
        Folder find = em.find(Folder.class, folderId);
        
        deleteFolder(userId, find);
    }
    
    public void deleteFolder(Long userId, Folder folder){
        em.remove(folder);
        
        folderChangeLogService.addLogRow(userId, folder, OperationTypeEnum.DETELE);
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
}
